package wang.wangby.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;
import wang.wangby.annotation.Remark;
import wang.wangby.lazydoc.model.ApiInfo;
import wang.wangby.utils.StringUtil;
import wang.wangby.utils.converter.JsonUtil;
import wang.wangby.utils.template.TemplateUtil;

@Slf4j
public class BaseController {

	@Autowired
	private Environment env;
	@Autowired
	private TemplateUtil templateUtil;
	@Autowired
	private JsonUtil jsonUtil;
	@Remark("当前controller的路径")
	private String path;

	
	public String $(String path) {
		return $(path,null);
	}

	public String $(String path, Object model) {
		return templateUtil.parseTemplate(path + ".html", defaultRoot(model));
	}

	public String $json(Object obj) {
		return jsonUtil.toString(obj);
	}

	private Map defaultRoot(Object obj) {
		//这个方法完全不耗时,就不加锁了
		if(path==null) {
			path=getPath();
		}
		
		Map map = new HashMap();
		map.put("path", path);
		if (obj == null) {
			return map;
		}
		
		if (obj instanceof Map) {
			map.putAll((Map) obj);
		}
		map.put(TemplateUtil.defaultName(obj), obj);
		return map;
	}

	//获得control所在路径
	synchronized private String getPath() {
		String path="";
		RequestMapping mapping = AnnotationUtils.getAnnotation(this.getClass(), RequestMapping.class);
		if (mapping.value() != null && mapping.value().length > 0) {
			path = mapping.value()[0];
			path = getValue(path);
			
		}
		log.debug("新增controller:"+path);
		//页面需要的路径不应该以/结尾
		if(path.endsWith("/")) {
			return path.substring(0,path.length()-1);
		}
		return path;
	}
	
	//获得配置值,不支持空格
	private String getValue(String key) {
		key =key.replaceAll("\\s+", "");
		if (!key.startsWith("$")) {
			return key;
		}
	
		key=key.substring(2, key.length()-1);
		String[] keys = key.trim().split(":");
		if(keys.length==2) {
			return env.getProperty(keys[0], keys[1]);
		}
		return env.getProperty(key);
	}
}
